import { useEffect, useLayoutEffect, useState } from "react";
function EffectComparison() {
  const [show, setShow] = useState(false);

  // 使用 useEffect - 会看到闪烁
  useEffect(() => {
    console.log('useEffect executed');
    if (show) {
      const element = document.getElementById("effect-box");
      element.style.transform = "translateX(200px)";
    }
  }, [show]);

  // 使用 useLayoutEffect - 无闪烁
  useLayoutEffect(() => {
    console.log('useLayoutEffect executed');
    if (show) {
      const element = document.getElementById("layout-effect-box");
      element.style.transform = "translateX(200px)";
    }
  }, [show]);

  console.log('Component rendering');

  return (
    <div style={{ padding: "20px" }}>
      <button onClick={() => setShow(!show)}>Toggle Boxes</button>

      <div style={{ display: "flex", gap: "20px", marginTop: "20px" }}>
        <div>
          <h3>useEffect (有闪烁):</h3>
          <div
            id="effect-box"
            style={{
              width: "100px",
              height: "100px",
              background: "lightblue",
              transition: "transform 0.3s",
            }}
          >
            useEffect
          </div>
        </div>

        <div>
          <h3>useLayoutEffect (无闪烁):</h3>
          <div
            id="layout-effect-box"
            style={{
              width: "100px",
              height: "100px",
              background: "lightcoral",
              transition: "transform 0.3s",
            }}
          >
            useLayoutEffect
          </div>
        </div>
      </div>
    </div>
  );
}

export default EffectComparison;